#include "NetwrokUtils.h"
#include <QCoreApplication>
#include <QAuthenticator>
#include <QNetworkProxy>
#include <QDebug>

NetwrokUtils::NetwrokUtils(QObject *parent)
    : QObject(parent)
    , m_networkManager(new QNetworkAccessManager(this))
    , m_timeout(30000) // 默认30秒超时
    , m_currentReply(nullptr)
    , m_isSyncRequest(false)
    , m_eventLoop(nullptr)
    , m_requestSuccess(false)
{
    connect(&m_timer, &QTimer::timeout, this, &NetwrokUtils::onTimeout);

    // 处理认证
    connect(m_networkManager, &QNetworkAccessManager::authenticationRequired,
            this, [this](QNetworkReply *reply, QAuthenticator *authenticator) {
                Q_UNUSED(reply)
                authenticator->setUser(m_username);
                authenticator->setPassword(m_password);
            });
}

NetwrokUtils::~NetwrokUtils()
{
    if (m_currentReply) {
        m_currentReply->abort();
        m_currentReply->deleteLater();
    }
}

void NetwrokUtils::setServerUrl(const QString &url)
{
    m_serverUrl = url;
    if (!m_serverUrl.endsWith("/")) {
        m_serverUrl.append("/");
    }
}

void NetwrokUtils::setAuthInfo(const QString &username, const QString &password)
{
    m_username = username;
    m_password = password;
}

void NetwrokUtils::setTimeout(int milliseconds)
{
    m_timeout = milliseconds;
}

bool NetwrokUtils::sendRequestSync(const QString &endpoint, const QJsonObject &requestData, QJsonObject &responseData, QString &errorString)
{
    if (m_serverUrl.isEmpty()) {
        errorString = "Server URL is not set";
        return false;
    }

    m_isSyncRequest = true;
    m_requestSuccess = false;
    m_syncError.clear();
    m_syncResponse = QJsonObject();

    // 创建事件循环用于同步等待
    QEventLoop eventLoop;
    m_eventLoop = &eventLoop;

    // 发送异步请求
    sendRequestAsync(endpoint, requestData);

    // 启动超时定时器
    m_timer.start(m_timeout);

    // 进入事件循环等待请求完成或超时
    eventLoop.exec();

    // 清理
    m_timer.stop();
    m_eventLoop = nullptr;
    m_isSyncRequest = false;

    if (m_requestSuccess) {
        responseData = m_syncResponse;
        return true;
    } else {
        errorString = m_syncError;
        return false;
    }
}

void NetwrokUtils::sendRequestAsync(const QString &endpoint, const QJsonObject &requestData)
{
    if (m_serverUrl.isEmpty()) {
        emit requestError("Server URL is not set");
        return;
    }

    // 创建请求
    QNetworkRequest request = createRequest(endpoint);

    // 将JSON数据转换为QByteArray
    QJsonDocument doc(requestData);
    QByteArray data = doc.toJson(QJsonDocument::Compact);

    // 发送POST请求
    m_currentReply = m_networkManager->post(request, data);

    // 连接完成和错误信号
    connect(m_currentReply, &QNetworkReply::finished, this, [this]() {
        onReplyFinished(m_currentReply);
    });

    connect(m_currentReply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error), this, [](QNetworkReply::NetworkError error) {
        Q_UNUSED(error)
        // 错误处理在onReplyFinished中统一进行
    });

    // 启动超时定时器
    m_timer.start(m_timeout);
}

void NetwrokUtils::onReplyFinished(QNetworkReply *reply)
{
    m_timer.stop();

    // 处理响应
    processReply(reply);

    // 清理
    reply->deleteLater();
    if (reply == m_currentReply) {
        m_currentReply = nullptr;
    }
}

void NetwrokUtils::onTimeout()
{
    if (m_currentReply) {
        m_currentReply->abort();
        m_syncError = "Request timeout";
        m_requestSuccess = false;

        if (m_eventLoop && m_eventLoop->isRunning()) {
            m_eventLoop->quit();
        } else {
            emit requestError(m_syncError);
        }
    }
}

QNetworkRequest NetwrokUtils::createRequest(const QString &endpoint)
{
    QString url = m_serverUrl + endpoint;
    QNetworkRequest request(url);

    // 设置HTTP头
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setHeader(QNetworkRequest::UserAgentHeader, "Qt MES Communicator");

    // // 如果需要认证，添加认证头
    // if (!m_username.isEmpty() && !m_password.isEmpty()) {
    //     QString credentials = m_username + ":" + m_password;
    //     QString base64Credentials = credentials.toUtf8().toBase64();
    //     request.setRawHeader("Authorization", "Basic " + base64Credentials);
    // }

    return request;
}

void NetwrokUtils::processReply(QNetworkReply *reply)
{
    // 检查网络错误
    // 检查网络错误
    if (reply->error() != QNetworkReply::NoError) {
        QString errorString = reply->errorString();

        if (m_isSyncRequest) {
            m_syncError = errorString;
            m_requestSuccess = false;
            if (m_eventLoop && m_eventLoop->isRunning()) {
                m_eventLoop->quit();
            }
        } else {
            emit requestError(errorString);
        }
        return;
    }

    // 读取响应数据
    QByteArray responseData = reply->readAll();

    // 解析JSON响应
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(responseData, &parseError);

    if (parseError.error != QJsonParseError::NoError) {
        QString errorString = "JSON parse error: " + parseError.errorString();

        if (m_isSyncRequest) {
            m_syncError = errorString;
            m_requestSuccess = false;
            if (m_eventLoop && m_eventLoop->isRunning()) {
                m_eventLoop->quit();
            }
        } else {
            emit requestError(errorString);
        }
        return;
    }

    if (!doc.isObject()) {
        QString errorString = "Response is not a JSON object";

        if (m_isSyncRequest) {
            m_syncError = errorString;
            m_requestSuccess = false;
            if (m_eventLoop && m_eventLoop->isRunning()) {
                m_eventLoop->quit();
            }
        } else {
            emit requestError(errorString);
        }
        return;
    }

    QJsonObject jsonResponse = doc.object();

    // 处理同步请求
    if (m_isSyncRequest) {
        m_syncResponse = jsonResponse;
        m_requestSuccess = true;
        if (m_eventLoop && m_eventLoop->isRunning()) {
            m_eventLoop->quit();
        }
    } else {
        // 发出异步完成信号
        emit requestCompleted(jsonResponse);
    }
}


